const qs = require('qs')
const Mock = require('mockjs')
const config = require('../utils/config')
const { apiPrefix } = config

let usersListData = Mock.mock({
  'data|800-10000': [
    {
      id: '@id',
      name: '@cname',
      nickName: '@last',
      phone: /^1[34578]\d{9}$/,
      'age|11-99': 1,
      address: '@county(true)',
      isMale: '@boolean',
      email: '@email',
      createTime: '@datetime',
      avatar () {
        return Mock.Random.image('100x100', Mock.Random.color(), '#757575', 'png', this.name.substr(0, 1))
      },
    },
  ],
})


let database = usersListData.data

const userPermission = {
  DEFAULT: [
    'dashboard', 'chart',
  ],
  ADMIN: [
    'dashboard', 'users', 'UIElement', 'UIElementIconfont', 'chart',
  ],
  DEVELOPER: ['dashboard', 'users', 'UIElement', 'UIElementIconfont', 'chart'],
}

const adminUsers = [
  {
    id: 0,
    username: 'admin',
    password: 'admin',
    permissions: userPermission.ADMIN,
  }, {
    id: 1,
    username: 'guest',
    password: 'guest',
    permissions: userPermission.DEFAULT,
  }, {
    id: 2,
    username: '吴彦祖',
    password: '123456',
    permissions: userPermission.DEVELOPER,
  },
  {
    id: 3,
    username: '梦江南',
    password: '123456',
    permissions: userPermission.ADMIN,
  },
  {
    id: 4,
    username: '刘乔可',
    password: '123456',
    permissions: userPermission.ADMIN,
  },
  {
    id: 5,
    username: '李树东',
    password: '123456',
    permissions: userPermission.ADMIN,
  },
  {
    id: 6,
    username: '杨智珺',
    password: '123456',
    permissions: userPermission.ADMIN,
  },
  {
    id: 7,
    username: '叶星魁',
    password: '123456',
    permissions: userPermission.ADMIN,
  },{
    id: 8,
    username: '宝哥',
    password: '123456',
    permissions: userPermission.ADMIN,
  },
]

const queryArray = (array, key, keyAlias = 'key') => {
  if (!(array instanceof Array)) {
    return null
  }
  let data

  for (let item of array) {
    if (item[keyAlias] === key) {
      data = item
      break
    }
  }

  if (data) {
    return data
  }
  return null
}

const NOTFOUND = {
  message: 'Not Found',
  documentation_url: 'http://localhost:8000/request',
}

module.exports = {

  // [`POST /user/login`] (req, res) {
  //   const { username, password } = req.query;
  //   const user = adminUsers.filter((item) => item.username === username)
  //   if (user.length > 0 && user[0].password === password) {
  //     const now = new Date()
  //     now.setDate(now.getDate() + 1)
  //     res.cookie('token', JSON.stringify({ id: user[0].id, deadline: now.getTime() }), {
  //       maxAge: 900000,
  //       httpOnly: true,
  //     })
  //     res.json({ success: true, message: 'Ok' })
  //   } else {
  //     res.status(400).end()
  //   }
  // },

  //token认证
  'POST /mock/oauth/token' (req, res) {
    // const userItem = getBody(req)
    const response = {
      success: true,
      access_token: 'i am a test access_token'
    }
    res.json(response)
  },

  //登录
  [`POST /mock/user/login`] (req, res) {
    const { username, password, access_token } = req.query;
    const user = adminUsers.filter((item) => item.username === username);
    const response = {
      success: false,
      msg: '',
      username : '',
      access_token : ''
    }
    if(user.length > 0){
      if(user[0].password === password) {
        //
        // const now = new Date();
        // now.setDate(now.getDate() + 1);
        // res.cookie('token', JSON.stringify({id: user[0].id, deadline: now.getTime() }),
        //             {
        //               maxAge : 900000,
        //               httpOnly : true
        //             })

        response.msg = '登录成功'
        response.success = true
        response.username = username
      }else {
        response.msg = '密码不正确'
      }
    } else {
      response.msg = '用户不存在'
    }
    res.json(response)
  },

  //退出登录
  'GET /mock/user/logout' (req, res) {
    // console.log('注销cookie');
    res.clearCookie('token')
    const response = {
      success: false,
      msg: ''
    }
    response.msg = '注销成功'
    response.success = true

    res.json(response)
  },

  [`GET /mock/user`] (req, res) {
    const cookie = req.headers.cookie || ''
    const cookies = qs.parse(cookie.replace(/\s/g, ''), { delimiter: ';' })
    const response = {}
    const user = {}
    if (!cookies.token) {
      res.status(200).send({ message: 'Not Login' })
      return
    }
    const token = JSON.parse(cookies.token)
    if (token) {
      response.success = token.deadline > new Date().getTime()
    }
    if (response.success) {
      const userItem = adminUsers.filter(_ => _.id === token.id)
      if (userItem.length > 0) {
        user.permissions = userItem[0].permissions
        user.username = userItem[0].username
        user.id = userItem[0].id
      }
    }
    response.user = user
    res.json(response)
  },

  'GET /mock/users' (req, res) {
    const { query } = req
    let { pageSize, page, ...other } = query
    pageSize = pageSize || 10
    page = page || 1

    let newData = database
    res.status(200).json(newData)
    // for (let key in other) {
    //   if ({}.hasOwnProperty.call(other, key)) {
    //     newData = newData.filter((item) => {
    //       if ({}.hasOwnProperty.call(item, key)) {
    //         if (key === 'address') {
    //           return other[key].every(iitem => item[key].indexOf(iitem) > -1)
    //         } else if (key === 'createTime') {
    //           const start = new Date(other[key][0]).getTime()
    //           const end = new Date(other[key][1]).getTime()
    //           const now = new Date(item[key]).getTime()
    //
    //           if (start && end) {
    //             return now >= start && now <= end
    //           }
    //           return true
    //         }
    //         return String(item[key]).trim().indexOf(decodeURI(other[key]).trim()) > -1
    //       }
    //       return true
    //     })
    //   }
    // }

    // res.status(200).json({
    //   data: newData.slice((page - 1) * pageSize, page * pageSize),
    //   total: newData.length,
    // })
    // let data: newData.slice((page - 1) * pageSize, page * pageSize)
    // let data = newData.slice((page - 1) * pageSize, page * pageSize);
    // let total = newData.length;

    // console.log('===mock+users===');
    // let data = database
    // res.json(data);
    // res.status(200).end();
  },

  [`POST ${apiPrefix}/user`] (req, res) {
    const newData = req.body
    newData.createTime = Mock.mock('@now')
    newData.avatar = newData.avatar || Mock.Random.image('100x100', Mock.Random.color(), '#757575', 'png', newData.nickName.substr(0, 1))
    newData.id = Mock.mock('@id')

    database.unshift(newData)

    res.status(200).end()
  },

  [`GET ${apiPrefix}/user/:id`] (req, res) {
    const { id } = req.params
    const data = queryArray(database, id, 'id')
    if (data) {
      res.status(200).json(data)
    } else {
      res.status(404).json(NOTFOUND)
    }
  },

  [`DELETE /mock/delete`] (req, res) {
    const { id } = req.query
    const data = queryArray(database, id, 'id')
    if (data) {
      database = database.filter((item) => item.id !== id)
      res.status(200).json(database)
    } else {
      res.status(404).json(NOTFOUND)
    }
  },

  [`PATCH ${apiPrefix}/user/:id`] (req, res) {
    const { id } = req.params
    const editItem = req.body
    let isExist = false

    database = database.map((item) => {
      if (item.id === id) {
        isExist = true
        return Object.assign({}, item, editItem)
      }
      return item
    })

    if (isExist) {
      res.status(201).end()
    } else {
      res.status(404).json(NOTFOUND)
    }
  },
}
